package com.sunseaypw.web.filter;

import com.sunseaypw.web.WebBase;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/* 为过滤所有请求 */
//@WebFilter(urlPatterns = "/*") 
/* 过滤/user/为前缀的请求 */
//@WebFilter(urlPatterns = "/user/*")
@WebFilter(filterName = "Filter111") 
public class Filter111 implements Filter {
    @Override
    public void init(FilterConfig filterConfig)throws ServletException{
        System.out.println(String.format("%s Filter111-init  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));
    }
    @Override
    public void doFilter(ServletRequest req,ServletResponse rsp,FilterChain chain)
        throws java.io.IOException, ServletException{
        System.out.println(String.format("%s Filter111-doFilter 进入  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));        
        req.setAttribute("filter",(req.getAttribute("filter")==null?"":req.getAttribute("filter")) + "  Filter111 Filter111我来了");
        HttpServletResponse rsp111=(HttpServletResponse)rsp;
        rsp111.setHeader("content-type", "text/css");
        chain.doFilter(req,rsp);     
        /* doFilter后面的代码会被执行，但若后续经过forward转发后则无法写入response */  
        var url= ((HttpServletRequest)req).getRequestURL();
        if(url.indexOf("/static/")==-1){
            rsp.setContentType("text/html");
            rsp.setCharacterEncoding("utf-8");      
            var pw = rsp.getWriter();
            pw.write("<h1>filter111尾部添加点料啊!</h1>");
            pw.flush();
        }         
        System.out.println(String.format("%s Filter111-doFilter 离开 线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));                
    }
    @Override 
    public void destroy(){
        System.out.println(String.format("%s Filter111-destroy  线程：%s",WebBase.getNowTime(), Thread.currentThread().getName()));
    }
}
